class Question < ActiveRecord::Base
	has_many :qa_details	
	belongs_to :user, :foreign_key => 'student_id'
	belongs_to :grade
	belongs_to :subject
	has_many :ratings

	[:initial, :asking, :read, :answered, :accepted].each do |key|
		named_scope key, lambda {
			{:conditions => {:status => key.to_s}}
		} 
	end

	named_scope :teacher_questions, lambda{|user_id|
		{
			:joins => %Q{				
				INNER JOIN grades_users gu ON questions.grade_id = gu.id
				INNER JOIN subjects_users su ON questions.subject_id = su.id
			},
			:conditions => ['gu.user_id = ?',user_id],
			:select => 'questions.*'			
		}
	}	

	named_scope :teacher_answered_questions, lambda{|user_id|
		{
			:joins => %Q{
				INNER JOIN qa_details qd ON questions.id = qd.question_id
				INNER JOIN grades_users gu ON qd.user_id = gu.user_id
				INNER JOIN subjects_users su ON qd.user_id = su.user_id
			},
			:conditions => ['qd.user_id = ? AND questions.grade_id = gu.id AND questions.subject_id = su.id',user_id],
			:select => 'questions.*'			
		}
	}

	named_scope :question, lambda{|question_id|
		{
			:conditions => ['questions.id = ?',question_id]
		}
	}

	named_scope :teacher_answered_for_student, lambda{|student_id|
		{
			:joins => %Q{
				INNER JOIN qa_details qd ON questions.id = qd.question_id
				INNER JOIN users ON qd.user_id = users.id
			},			
			:conditions => ['qd.rely_to = ?',student_id],
			:select => 'distinct users.*'			
		}	
	}	
end
